
from typing import Optional
from homeassistant.const import (EVENT_HOMEASSISTANT_START,
                                 EVENT_HOMEASSISTANT_STOP, EVENT_STATE_CHANGED,
                                CONF_USERNAME,CONF_PASSWORD,CONF_NAME,CONF_DEVICES,ATTR_ENTITY_ID,ATTR_FRIENDLY_NAME)
import homeassistant.helpers.config_validation as cv
import voluptuous as vol
from  .VioceApp import VioceApp
import logging
_LOGGER = logging.getLogger(__name__)

from .const import CONF_SELECT,DOMAIN
CONFIG_SCHEMA = vol.Schema({
    DOMAIN: vol.Schema({
        vol.Optional(CONF_USERNAME): cv.string,
        vol.Optional(CONF_PASSWORD): cv.string,
        vol.Optional(CONF_NAME,default='voice'): cv.string,
        vol.Optional(CONF_SELECT,default= True): cv.boolean,
        vol.Optional(CONF_DEVICES,default=[]):
            vol.All(cv.ensure_list,[{
                vol.Required(ATTR_ENTITY_ID): cv.string,
                vol.Required(ATTR_FRIENDLY_NAME): cv.string
        }]),
    }, extra=vol.ALLOW_EXTRA),
}, extra=vol.ALLOW_EXTRA)


def setup(hass, config):
    conf = config[DOMAIN]
    mqtt_client = VioceApp(hass,conf)
    
    def on_state_changed(event):
        #obj = json.dumps(states)
        #print(obj)
        mqtt_client.ha_state_changed(event)

    """启动方法"""
    def ha_start(event):
        mqtt_client.connect_mqtt()
        #mqtt.client.loop_forever()
        mqtt_client.client.loop_start()

   

    hass.bus.async_listen(EVENT_STATE_CHANGED, on_state_changed)

    hass.bus.async_listen(EVENT_HOMEASSISTANT_START, ha_start)


    return True
